#!/bin/bash

: '

https://github.com/alireza0/x-ui/releases/download/1.8.9/x-ui-linux-arm64.tar.gz		# 说这个不稳定
https://github.com/FranzKafkaYu/x-ui/releases/download/0.3.4.4/x-ui-linux-arm64.tar.gz	# 给换成这个试试

'

SWNAME=x-ui
SWVER=0.3.4.4

# 注意安装顺序，后装者依赖前装者
DEB_PATH1=./downloads/${SWNAME}-${SWVER}.tar.gz

DIR_DESKTOP_FILES=/usr/share/applications
DSK_FILE=${SWNAME}.desktop
DSK_PATH=${DIR_DESKTOP_FILES}/${DSK_FILE}
app_dir=/opt/apps/${SWNAME}

action=$1
if [ "$action" == "" ]; then action=安装; fi

. ./scripts/common.sh

function sw_download() {
	tmpdns=`cd /exbin && droidexec ./vm_getHostByName.sh ${GITHUB_PROXY_HOST}`
	exit_if_fail $? "DNS解析失败"
	echo "$tmpdns" >> /etc/hosts

	case "${CURRENT_VM_ARCH}" in
		"arm64")
			swUrl="${GITHUB_PROXY_HTTP}https://github.com/FranzKafkaYu/x-ui/releases/download/0.3.4.4/x-ui-linux-arm64.tar.gz"
			download_file2 "${DEB_PATH1}" "${swUrl}"
			exit_if_fail $? "下载失败，网址：${swUrl}"
		;;
		*) exit_unsupport ;;
	esac
}

function sw_install() {

	sudo apt-get install -y socat
	exit_if_fail $? "依赖库 socat 安装失败"

	mkdir -p ${app_dir}

	echo "正在解压. . ."
	tar -xzf ${DEB_PATH1} --overwrite -C ${app_dir}/..
	exit_if_fail $? "安装失败，软件包：${DEB_PATH1}"

	# s 权限, 表示运行这个程序时需要有root权限
	chmod +s ${app_dir}/x-ui
	exit_if_fail $? "s权限添加失败"

	chmod -R 777 ${app_dir}
	exit_if_fail $? "权限添加失败"

	mkdir -p /etc/x-ui 2>/dev/null
	exit_if_fail $? "/etc/x-ui 目录创建失败"

	chmod -R 777 /etc/x-ui
	exit_if_fail $? "权限添加失败"

	# proot环境中不需要这两个文件
	rm -rf ${app_dir}/x-ui.sh
	rm -rf ${app_dir}/x-ui.service
}

function sw_create_desktop_file() {

	echo "正在生成启动程序"
	tmpfile=/usr/bin/${SWNAME}
	cat <<- EOF > ${tmpfile}
		#!/bin/bash
		APPNAME_WEB_PORT=54321
		echo "x-ui控制面板地址：" > /tmp/msg.txt
		/exbin/tools/vm_ip2link.sh "http://" ":\${APPNAME_WEB_PORT}">>/tmp/ip.txt
		echo "" >>/tmp/msg.txt
		echo "" >>/tmp/msg.txt
		gxmessage -title "x-ui" -file /tmp/msg.txt -center &
		cd ${app_dir} && env XRAY_VMESS_AEAD_FORCED=false ${app_dir}/x-ui
	EOF
	chmod 755 ${tmpfile}

	echo "正在生成桌面文件"
	cat <<- EOF > ${DSK_PATH}
		[Desktop Entry]
		Name=x-ui
		Comment=带网页控制端的Xray
		Exec=x-ui
		Path=${app_dir}
		Terminal=true
		Type=Application
	EOF
	cp2desktop ${DSK_PATH}

	gxmessage -title "提示"     $'\n安装完成\n\n'  -center
}

if [ "${action}" == "卸载" ]; then
	# echo "暂不支持卸载"
	# exit 1
	rm -rf /usr/bin/${SWNAME}
	rm -rf ${DEB_PATH1} ${app_dir}
	rm -rf /etc/x-ui
	rm2desktop ${DSK_FILE}
	apt-get clean
else
	sw_download
	sw_install
	sw_create_desktop_file
fi

